package com.lzc.mall.product.service.impl;

import org.checkerframework.checker.units.qual.A;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzc.common.utils.PageUtils;
import com.lzc.common.utils.Query;

import com.lzc.mall.product.dao.CategoryDao;
import com.lzc.mall.product.entity.CategoryEntity;
import com.lzc.mall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * 获取所有分类数据的树形结构
     * @return 树形结构
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1. 查询所有分类
        List<CategoryEntity> entities = this.baseMapper.selectList(null);

        //2. 组装成树形结构
        // 2.1 找一级分类
        List<CategoryEntity> level1Menus = entities.stream()
                .filter((categoryEntity) -> categoryEntity.getParentCid() == 0)
                .map(categoryEntity -> {
                    // 找到该分类的所有子分类
                    categoryEntity.setChildren(getChildrens(categoryEntity,entities));
                    return categoryEntity;
                })
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());

        // 2.2 找到下一级分类

        return level1Menus;
    }

    /**
     * 邏輯刪除菜單
     * @param asList
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {

        //TODO 1.检查当前删除的菜单，是否被別的地方引用

        baseMapper.deleteBatchIds(asList);
    }


    // 递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){


        List<CategoryEntity> children = all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId())
                .map(categoryEntity -> {
                    // 递归继续查找当前菜单的子菜单
                    categoryEntity.setChildren(getChildrens(categoryEntity,all));
                    return categoryEntity;
                })
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());

        return children;
    }
}